from flask import  Flask, render_template,request,escape
import requests
import matplotlib.pyplot as plt
import json
from weatherapi import weather

app = Flask(__name__)
def log_request(req:"flask request",res:str):
  with open("vsearch.log","a") as log:
    print(req.form,req.host_url,req.remote_addr,file=log,sep="|")


@app.route('/',methods=["GET"])
def hello() -> str:
  return "欢迎回来"

@app.route('/entry',methods=['post','get'])
def hello_entry():
  user = request.form.get("user")
  log_request(request,user)
  return render_template('entry.html')

@app.route("/login",methods=['get'])
def index()-> 'html':
  title ='welcome'
  return render_template("login.html",the_title=title)


@app.route("/we",methods=["post"])
def we():
  key='18ef7dd6aeefc21dade574262c00f213'
  city='440100'
  extensions='base'
  a=weather(key,city,extensions)
  b=a['lives'][0]['city']
  c=a['lives'][0]['weather']
  d=a['lives'][0]['temperature']
  e=a['lives'][0]['windpower']
  f=a['lives'][0]['humidity']
  return render_template('entry.html',city=str(b),weather=str(c),temperature=str(d),windpower=str(e),humidity=str(f))

@app.route("/viewlog")
def view_log():
  contents=[]
  with open("vsearch.log","r") as log:
    for line in log:
      contents.append([])
      for item in line.split("|"):
        contents[-1].append(escape(item))
    titles= ["Formdata","Host_url","Remote_addr"]
  return render_template('view.html',the_data=contents,the_titles=titles)
  

if __name__ == '__main__':
  app.run(debug= True)